//
//  BaseWebViewController.m
//  jingdongfang
//
//  Created by MTiMac01 on 2017/11/22.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "BaseWebViewController.h"
#import <WebKit/WebKit.h>
@interface BaseWebViewController ()<WKNavigationDelegate>{
    NSString *urlStr;
}

@property (nonatomic, strong) WKWebView *webView;

@end

@implementation BaseWebViewController

- (instancetype)initWithUrl:(NSString *)url
{
    if (self = [super init])
    {
        urlStr = url;
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];

    if ([urlStr isValidUrl])
    {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (WKWebView *)webView
{
    if (!_webView)
    {
        _webView = [[WKWebView alloc] init];
        _webView.navigationDelegate = self;
        _webView.backgroundColor = [UIColor clearColor];
        _webView.allowsBackForwardNavigationGestures = YES;
    }
    return _webView;
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    if ([webView.URL.absoluteString isEqualToString:@"https://st.360buyimg.com/common/downLoadCommon/downLoadAppIOSMPage.html"]) {
        //        /[0-9a-zA-Z]+.html
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [webView evaluateJavaScript:@"document.title;" completionHandler:^(id Result, NSError * error) {
        NSString *title = Result;
        self.title = title;
    }];
}

-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if (!navigationAction.targetFrame.isMainFrame)
    {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

- (void)ig_leftBackButtonPressed:(id)sender {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
